<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 搜索与添加 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="danger" class="button-jd" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" :stripe="true">
        <!-- 添加索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽！！！ -->
          <template slot-scope="scope">
            <el-switch
              @change="userStateChanged(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#ff4949"
              inactive-color="grey"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              @click="removeUserById(scope.row.id)"
              type="info"
              size="mini"
              icon="el-icon-scissors"
            ></el-button>
            <el-button type="dark" size="mini" icon="el-icon-tickets" @click="setRole(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog @close="addDialogClosed" title="添加用户" :visible.sync="addDialogVisible" width="30%">
      <!-- 主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <!-- prop指的是校验规则 -->
        <!-- rules是全部的校验规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      @close="editDialogClosed"
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <span>
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="60px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 修改对话框按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog @close="setRoleClosed" title="分配角色" :visible.sync="setRoleDialogVisible" width="30%">
      <div>
        <p>当前用户:{{userInfo.username}}</p>
        <p>当前角色:{{userInfo.role_name}}</p>
        <p>
          分配角色:
          <el-select v-model="selectedRoleId" placeholder="请选择新的角色">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //   自定义校验规则
    var checkEmail = (rules, value, cb) => {
      const regEmail = /^([a-zA-z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      } else {
        cb(new Error("请输入合法邮箱"))
      }
    }
    var checkMobile = (rules, value, cb) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        //   直接使用cb表示调用成功
        return cb()
      } else {
        //   直接使用cb Error表示调用失败
        cb(new Error("请输入合法手机号"))
      }
    }

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 20, message: "用户名的长度在3到10", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 20, message: "密码的长度在3到10", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 3, max: 20, message: "邮箱的长度在3到10", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 3, max: 20, message: "手机号的长度在3到20", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          // required表示必填项
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 3, max: 20, message: "邮箱的长度在3到10", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 3, max: 20, message: "手机号的长度在3到20", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: "",
    }
  },

  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      })
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.console.error("获取列表失败！")
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },
    handleSizeChange(newSize) {
      this, (this.queryInfo.pagesize = newSize)
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userInfo) {
      //   console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      //   console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error("更新失败！")
      } else {
        this.$message.success("更新成功！")
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      // 表单预校验
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) {
        } else {
          const { data: res } = await this.$http.post("users", this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error("添加用户失败!")
          } else {
            this.$message.success("添加用户成功!")
            this.addDialogVisible = false
            this.getUserList()
          }
        }
      })
    },
    async showEditDialog(id) {
      this.editDialogVisible = true
      //   console.log(id)
      const { data: res } = await this.$http.get("users/" + id)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error("查询失败!")
      } else {
        this.$message.success("查询成功!")
        this.editForm = res.data
      }
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) {
        } else {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            { email: this.editForm.email, mobile: this.editForm.mobile }
          )
          if (res.meta.status !== 200) {
            this.$message.error("更新失败！")
          } else {
            this.editDialogVisible = false
            this.getUserList()
            this.$message.success("更新成功！")
          }
        }
      })
    },
    async removeUserById(id) {
      // confirm也是element ui的内容
      const a = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err
      })
      //   console.log(a)
      if (a !== "confirm") {
        this.$message.info("已取消")
      } else {
        const { data: res } = await this.$http.delete("users/" + id)
        if (res.meta.status !== 200) {
          this.$message.error("删除失败")
        } else {
          this.$message.success("删除成功")
          this.getUserList()
        }
      }
    },
    async setRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status != 200) {
        this.$message.error("获取失败")
      } else {
        this.rolesList = res.data
        this.setRoleDialogVisible = true
      }
    },
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        this.$message.error("分配角色错误")
      } else {
        const { data: res } = await this.$http.put(
          `users/${this.userInfo.id}/role`,
          { rid: this.selectedRoleId }
        )
        if (res.meta.status !== 200) {
          this.$message.error("更新角色错误")
        } else {
          this.$message.success("分配角色成功")
          this.getUserList()
          this.setRoleDialogVisible = false
        }
      }
    },
    setRoleClosed() {
      this.selectedRoleId = ""
      this.userInfo = {}
    },
  },
}
</script>
<style lang="less" scoped>
.button-jd {
  background-color: #e83632;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  color: #e83632;
}
</style>
